<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus"  @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>
    <el-table :data="editionList">
      <el-table-column property="versionNo" label="版本号" width="220"></el-table-column>
      <el-table-column property="versionName" label="版本名称"></el-table-column>
      <el-table-column property="upgradeTip" label="更新提示（内容）"></el-table-column>
      <el-table-column property="upgradeTime" label="升级时间">
        <template #default="{ row }">
          {{ format.FormatDate(row.upgradeTime) }}
        </template>
      </el-table-column>
      <el-table-column property="status" label="状态">
        <template #default="{ row }">
          <el-tag v-if="row.status == 0">正常</el-tag>
          <el-tag type="danger" v-if="row.status == 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="type" label="固件类型">
        <template #default="{ row }">
          <p v-if="row.type == 1">网关固件</p>
          <p v-if="row.type == 2">逆变器固件</p>
        </template>
      </el-table-column>

      <el-table-column property="remark" label="备注"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="Edit" v-if="scope.row.status == 0"
            @click="upgrade(scope.row)">升级</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区 -->
    <div class="block" style="margin: 20px">
      <el-pagination background @size-change="editionSizeChange" @current-change="editionCurrentChange"
        :current-page="editionData.page" :page-size="editionData.pagesize" :page-sizes="[2, 4, 6, 8, 10]"
        layout="sizes, prev, pager, next,total, jumper" :total="editionData.total"> </el-pagination>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="版本号" prop="versionNo">
          <el-input v-model="form.versionNo" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="更新内容" prop="upgradeTip">
          <el-input v-model="form.upgradeTip" placeholder="请输入更新内容" />
        </el-form-item>
        <el-form-item label="固件类型" prop="type">
          <el-select v-model="form.type" placeholder="固件类型" style="margin-right: 10px">
            <el-option v-for="item in firmwareType" :key="item.key" :label="$t('licence.fir_type' + item.key)"
              :value="item.key"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="更新备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注" />
        </el-form-item>
        <el-form-item label="状态" v-if="statusS">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="pakeageBin" label=" 固件升级包">
          <el-button type="primary" @click="submitFileForm">点我上传升级包</el-button>
          <el-upload v-model="form.pakeageBin" ref="uploadRef" :limit="1" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :accept="form.type == 1 ? '.gwbin' : '.psbin'" :auto-upload="false" drag>
            <el-icon><UploadFilled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 升级弹框 -->
    <el-dialog title="升级版本" v-model="upgradeShow" width="70%">
      <div class="time-box">
        <!-- 电站状态 -->
        <el-select style="margin: 0 20px" v-model="powerState" :placeholder="$t('licence.status')" clearable
          @change="powerStateChanged">
          <el-option v-for="item in options" :key="item.key" :label="$t('licence.sta_type' + item.key)" :value="item.key">
          </el-option>
        </el-select>
        <!-- 国家 -->
        <el-select v-if="adminShow" v-model="regionCode" placeholder="请选择国家" clearable @change="getAdd"
          style="margin-right: 10px">
          <el-option v-for="item in country" :key="item.regionCode" :label="lang == 1 ? item.regionNameEn : item.cityName"
            :value="item.regionCode"> </el-option>
        </el-select>
        <!-- 电站地点 -->
        <el-cascader placeholder="全部省份" v-model="label" :options="addOptions" clearable
          @change="addOptionsChanged"></el-cascader>
        <el-input class="input" v-model="powerName"></el-input>
        <el-button @click="onSubmit" type="primary" style="margin: 20px 0">{{ $t('licence.fau_Thequery') }}</el-button>
      </div>
      <el-table :data="powerStationList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="num" label="序号" width="120"> </el-table-column>
        <el-table-column prop="stationName" label="电站名称" width="180"> </el-table-column>
        <el-table-column prop="userName" label="联系人" width="120"> </el-table-column>
        <el-table-column prop="phone" label="联系方式" width="180"> </el-table-column>
        <el-table-column prop="email" label="联系邮箱"> </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
        <el-table-column prop="installedCapacity" label="装机功率（kW）" width="120"> </el-table-column>
        <el-table-column prop="state" label="当前状态" width="120">
          <template #default="scope">
            <p v-if="scope.row.state == 0">正常</p>
            <p v-if="scope.row.state == 1">异常</p>
            <p v-if="scope.row.state == 2">离线</p>
            <p v-if="scope.row.state == 3">告警</p>
          </template>
        </el-table-column>
        <el-table-column prop="days" label="运行时间" width="120"> </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block" style="margin: 20px">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryData.page" :page-size="queryData.pagesize" :page-sizes="[2, 4, 6, 8, 10]"
          layout=" prev, pager, next,total, jumper" :total="queryData.total"> </el-pagination>
      </div>
      <el-form ref="upgradeForm" :model="upgradeForm" :rules="rules" label-width="90px">
        <el-form-item label="更新备注" prop="remark">
          <el-input v-model="upgradeForm.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpgrade">确 定</el-button>
        <el-button @click="submitUpgradecancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name='Edition'>
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { getEditionLists, addEdition, xiugaiEdition, addByStation } from '@/api/system/edition/edition';
import { getToken } from '@/utils/auth';
import format from '@/utils/format';
import { getstationList, getAdds, getCountrys } from '@/api/homeIndex'; //升级获取电站列表
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

      const userInfo = ref({})
      const editionList = ref([]) //固件升级列表
      // 是否显示升级弹出层
      const upgradeShow = ref(false)
      // 是否显示弹出层
      const open = ref(false)
      // 弹出层标题
      const title = ref('')
      // 表单参数
      const statusS = ref(false)
      type formValue = {
        versionNo?: string;
        versionName?: string;
        upgradeTip?: string;
        type?: number;
        remark?: string;
        status?: number;
        pakeageBin?: string;
      }
      const form = ref<formValue>({})
      const firmwareType = [{  key: 1,},{  key: 2,},]
      // const fileType = ref('') //升级包的后缀名
      const upgradeForm = ref({
        remark:''
      })
      // 表单校验
      const rules = {
        versionNo: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
        versionName: [{ required: true, message: '版本名称不能为空', trigger: 'blur' }],
        upgradeTip: [{ required: true, message: '更新内容不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择固件类型', trigger: 'blur' }],
      }
      // 用户导入参数
      const upload = reactive({
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + '/solarFirmwareUpgradeVersion/upload',
      })
      const editionId = ref() //用户id
      // 表格信息
      // 下拉选择状态
      // 查询状态
      const powerState = ref(0) //查询下拉绑定默认字段
      const options = [{  key: 0,},{  key: 1,},{  key: 2,},{  key: 3,},{  key: 4,},]
      // 地址
      const label = ref([])
      const addOptions = ref([])
      //国家
      const country = ref([
        {
          regionCode:-1,
          regionNameEn:'',
        }
      ])
      const regionCode = ref()
      const adminShow =ref(false)  //国家选择显示与隐藏
      const powerName = ref('') //input输入
      const powerStationList = ref([]) //电站列表-表格
      // 固件升级分页
      const queryData = {
        page: 1, // 当前页码
        pagesize: 10,
        total: 0, // 总数
      }
      // 固件首页分页
      const editionData = {
        page: 1, // 当前页码
        pagesize: 10,
        total: 0, // 总数
      }
      // 选中数组
      const ids = ref([])
      // 非单个禁用
      const single = ref(true)
      // 非多个禁用
      const multiple = ref(true)
      const lang = ref('')
      const formRef = ref()
      const uploadRef = ref()

  onMounted(()=>{
    // 获取语言
    if (localStorage.getItem('locale') == 'en_US') {
      multiple.value = true;
    } else {
      multiple.value = false;
    }
    // 获取用户信息
    userInfo.value = JSON.parse(localStorage.getItem('userInfo') as string);
    // 获取用户信息
    getEditionList();
    // 获取省市级
    getAdd('');
    //获取国家
    getCountry();
    if ((userInfo.value.admin = true)) {
      adminShow.value = true;
    } else {
      adminShow.value = false;
    }
  })
    // 文件上传中处理
    const handleFileUploadProgress = (event:any, file:any, fileList:any) => {
      upload.isUploading = true;
    }
    // 文件上传成功处理
    const handleFileSuccess = (response:any, file:any, fileList:any) => {
      upload.isUploading = false;
      uploadRef.value?.clearFiles();
      form.value.pakeageBin = response.msg;
    }
    // 提交上传文件按钮
    const submitFileForm =() =>  {
      // ElMessage.error("请先上传升级包");
      uploadRef.value?.submit();
    }

    /** 新增按钮操作 */
    const handleAdd =() =>  {
      open.value = true;
      statusS.value = false;
      form.value = {};
      title.value = '添加版本';
    }
    // // 修改
    const handleUpdate = (val:any) => {
      open.value = true;
      if (val.id) {
        statusS.value = true;
      }
      form.value = val;
      title.value = '修改版本';
    }
    // 取消按钮
    const cancel = () => {
      open.value = false;
      getEditionList();
      form.value = {};
    }
    // 升级弹框取消
    const submitUpgradecancel = () => {
      upgradeShow.value = false;
    }
    // /** 提交按钮 */
    const submitForm = () => {
      formRef.value?.validate((valid) => {
        if (valid) {
          if (form.value.id) {
            xiugaiEdition(form.value, multiple.value).then((response) => {
              proxy?.$modal.msgSuccess(t('licence.use_updateXiugai'));
              open.value = false;
              getEditionList();
            });
          } else {
            addEdition(form.value, multiple.value).then((response) => {
              proxy?.$modal.msgSuccess('新增成功');
              open.value = false;
              getEditionList();
            });
          }
        }
      });
    }
    //升级弹框
    const upgrade = (val:any) => {
      editionId.value = val.id;
      // loading = true;
      upgradeShow.value = true;
      getpower();
    }
    // 升级按钮获取电站页面
    const getpower = async () => {
      let query = {
        address: label.value.join(','),
        pageNum: queryData.page,
        pageSize: queryData.pagesize,
        // stationName: powerName,
        searchValue: powerName.value,
        state: powerState.value - 1,
        country: regionCode.value,
        quickSearch: true,
      };
      const res = await getstationList(query);
      powerStationList.value = res.rows;
      queryData.total = res.total;
    }
    // 固件升级弹框里分页
    // 分页
    const handleSizeChange = (val:any) => {
      queryData.pagesize = val;
      getpower();
    }
    const handleCurrentChange = (val:any) => {
      queryData.page = val;
      getpower();
    }
    // 查询功能
    const onSubmit = () => {
      getpower();
    }
    // 状态下拉选择事件
    const powerStateChanged = (value:any) => {
      editionId.value = value;
      getpower();
    }
    // 获取国家
    const getCountry = async () => {
      let res = await getCountrys({});
      country.value = res.data;
    }
    // 省市级选择
    const getAdd = async(value:any) => {
      regionCode.value = value;
      getpower();
      let res = await getAdds({
        code: regionCode.value || userInfo.value.dept.countryCode,
        lang: 0,
      });
      addOptions.value = res.data;
    }
    // 地址下拉选择事件
    const addOptionsChanged = (value:any) =>  {
      label.value = value;
      getpower();
    }
    // 多选框选中数据
    const handleSelectionChange = (selection:any) =>  {
      ids.value = selection.map((item:any) => item.id);
      single.value = selection.length != 1;
      multiple.value = !selection.length;
    }
    // 升级 确认按钮
    const submitUpgrade = async () => {
      let data = {
        stationIds: ids.value.join(','),
        remark: upgradeForm.value.remark,
        versionId: editionId.value,
        lang: lang.value,
      };
      await addByStation(data);
      proxy?.$modal.msgSuccess('升级成功');

      upgradeShow.value = false;
      upgradeForm.value.remark = '';
    }

    // 获取升级信息列表
    const getEditionList = async () => {
      let res = await getEditionLists({
        pageNo: editionData.page,
        pageSize: editionData.pagesize,
      });
      editionData.total = res.data.total;
      editionList.value = res.data.list;
    }
    // 固件首页分页
    const editionSizeChange = (val:number) => {
      editionData.pagesize = val;
      getEditionList();
    }
    const editionCurrentChange = (val:number) => {
      editionData.page = val;
      getEditionList();
    }
</script>
<style lang="scss" scoped>
// 弹框里的分页
.block {
  // display: flex;
  display: -webkit-box;
  justify-content: end;
}

// 上传文件
::v-deep .el-upload-dragger {
  width: 220px;
  height: 110px;
  margin-top: 10px;
}

::v-deep .el-upload-dragger .el-icon-upload {
  margin: 0px 0 6px;
}

// ========
.time-box {
  margin: -20px 0 20px -10px;
}

// 设备序列号
.input {
  width: 200px;
  margin-left: 20px;
  margin-right: 20px;
}</style>
